package cn.itcast.controller;


import cn.itcast.domain.system.Module;
import cn.itcast.domain.system.User;
import cn.itcast.service.system.UserService;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
public class LoginController {

    @Autowired
    private UserService userService;

    @Autowired
    private HttpServletRequest request;

    @Autowired
    private HttpSession session;

    @RequestMapping("/login")
    public String login(String email, String password) {
        if (StringUtils.isEmpty(email) || StringUtils.isEmpty(password)) {
            request.setAttribute("error", "邮箱或密码不能为空");
            return "forward:/login.jsp";
        }
        //User user = userService.findByEmail(email);
        password = new Md5Hash(password, email, 2).toString();
        UsernamePasswordToken token = new UsernamePasswordToken(email,password);
        Subject subject = SecurityUtils.getSubject();
        /*if (user == null || !user.getPassword().equals(password)) {
            request.setAttribute("error", "用户名或密码错误");
            return "forward:/login.jsp";
        } else {
            session.setAttribute("loginUser", user);
            List<Module> list = userService.findModuleListByUser(user);
            session.setAttribute("modules", list);
            return "home/main";
        }*/
        //从shiro中获取当前登录人
        try {
            subject.login(token);
        } catch (AuthenticationException e) {
//            e.printStackTrace();
            request.setAttribute("error","邮箱或者密码有误");
            return "forward:login.jsp";
        }
        User user = (User) subject.getPrincipal();
        //把当前登录人放入到session
        session.setAttribute("loginUser",user);
        List<Module> moduleList = userService.findModuleListByUser(user);
        session.setAttribute("modules",moduleList);
        return "home/main";
    }

    //退出
    @RequestMapping(value = "/logout", name = "用户登出")
    public String logout() {
        SecurityUtils.getSubject().logout();   //登出
        return "forward:login.jsp";
    }

    @RequestMapping("/home")
    public String home() {
        return "home/home";
    }
}
